package com.ym.pms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ym.pms.model.SysUser;
import com.ym.pms.model.SysUserRole;
import com.ym.pms.service.SysUserRoleService;
import com.ym.pms.service.SysUserService;
import com.ym.pms.utils.JSONResult;
import com.ym.pms.utils.SmsUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 23:03 2020/12/23
 * @Modified:
 */
@Api(tags = "注册接口")
@RequestMapping("/register")
@RestController
public class RegisterController {
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @PostMapping("/user")
    @ApiOperation("注册普通用户")
    public JSONResult user(@RequestParam String phone,
                           @RequestParam String ticket,
                           @RequestParam String username,
                           @RequestParam String password) {
        boolean verify = SmsUtil.verify(phone, ticket);
        if (!verify) {
            return JSONResult.build(401, "验证码错误", "");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUId(Long.parseLong((String)username));
        sysUser.setUPassword(bCryptPasswordEncoder.encode(password));
        sysUser.setUPhoneno(phone);
        sysUser.setUStatus("0");
        sysUserService.save(sysUser);

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUId());
        sysUserRole.setRoleId(5L);
        sysUserRoleService.save(sysUserRole);

        return JSONResult.build(200, "注册成功", sysUser.toString());
    }

    @PostMapping("/createAdmin")
    @ApiOperation("注册高权限用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名"),
            @ApiImplicitParam(name = "password", value = "密码"),
            @ApiImplicitParam(name = "permission", value = "权限代号")
    })
    public JSONResult createAdmin(
                           @RequestParam String username,
                           @RequestParam String password,
                           @RequestParam Long permission) {
        SysUser sysUser = new SysUser();
        sysUser.setUId(Long.parseLong((String)username));
        sysUser.setUPassword(bCryptPasswordEncoder.encode(password));
        sysUser.setUStatus("0");
        sysUserService.save(sysUser);

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getUId());
        sysUserRole.setRoleId(permission);
        sysUserRoleService.save(sysUserRole);

        return JSONResult.build(200, "注册成功", sysUser.toString());
    }
}
